<?php

namespace app\admin\controller\stock;

use app\common\controller\Backend;
use Exception;
use think\Db;
use app\admin\model\UserDepart;
use fast\Tree;

/**
 * 股权证交易管理
 *
 * @icon fa fa-circle-o
 */
class Flow extends Backend
{

    /**
     * Stock模型对象
     * @var \app\admin\model\StockTransfer
     */
    protected $model = null;
	protected $noNeedRight = ['depart'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\StockFlow;

    }
	
	public function index()
	{
		$groupIds = $this->auth->getGroupIds();
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

			$map = [];
			if($groupIds[0] == 3)
			{
				$map['from_depart'] = $this->auth->depart_id;
			}

            $list = $this->model
					->where($where)
					->where($map)
                    ->order('status asc, id desc')
                    ->paginate($limit);

            foreach ($list as &$row) {
				$from_depart = UserDepart::get($row['from_depart']);
				$row['from_depart'] = $from_depart['name'];
				$to_depart = UserDepart::get($row['to_depart']);
				$row['to_depart'] = $to_depart['name'];
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }

		$this->assignconfig("admin", ['groupid' => $groupIds[0]]);
        return $this->view->fetch();
	}
	
	public function del($ids = "")
	{
		$ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $list = $this->model->where('id', 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
					
					$sid = $v->sid;
					$row = model('stock')->get($sid);
					if ($row) {
						$row->status = 1;
						$row->save();
					}
					
                    $count += $v->delete();
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
	}
	
	public function review($ids = "")
	{
		$ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $list = $this->model->where('id', 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
					$v->status = 1;
					$v->checktime = time();
					
					$sid = $v->sid;
					$row = model('stock')->get($sid);
					if ($row) {
						$row->depart_id = $v['to_depart'];
						$row->status = 1;
						$row->save();
					}
					
					$user = model('user')->get($row['uid']);
					if ($user) {
						$user->depart_id = $v['to_depart'];
						$user->save();
					}
					
                    $count += $v->save();
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were updated'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
	}
	
	public function depart()
	{
		$groupList = collection(UserDepart::column('id,pid,name'))->toArray();

        Tree::instance()->init($groupList);
        $groupList = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
		
        $groupName = [];
        foreach ($groupList as $k => $v) {
            $groupName[$v['id']] = $v['name'];
        }
		
		echo json_encode($groupName);
		exit;
	}
}
